<script setup>

import { ref, inject } from 'vue';
import { ElMessage, ElMessageBox } from "element-plus";
import { Edit, Plus, Delete, Check, Search } from '@element-plus/icons-vue';

const http = inject('$http'),
	tools = inject('$tools'),
	router = inject('$router');

var adminForm = ref(),
	EditDrawer = ref(),
	showForm = ref(false),
	fetching = ref(false),
	rolesList = ref(null),
	submiting = ref(false),
	processing = ref(false),
	dataList = ref({ total: 0, items: [] }),
	query = ref({ username: '', realname: '', page: 1, size: 10 });

var queryParams = {},
	queryChanged = false,
	willUpdateRow = null,
	states = {
		0: { class: 'danger', label: '删除' },
		1: { class: 'success', label: '正常' },
		2: { class: 'warning', label: '禁用' },
	};

const sizeOptions = [10, 20, 30]

const fetch = async function (inQuery) {
	if (typeof inQuery === 'object') {
		query.value = Object.assign(query.value, {
			page: inQuery.page, size: inQuery.size
		});
	}
	if (queryChanged) {
		query.value.page = 1;
		queryChanged = false;
	}
	if (JSON.stringify(queryParams) !== JSON.stringify(query.value)) {
		router.push({ query: query.value })
		// 同步路由参数记录
		queryParams = JSON.parse(JSON.stringify(query.value));
	}
	fetching.value = true;
	const res = await http.get('/rbac/admin', query.value);
	fetching.value = false;
	if (res && res.code === 200) {
		dataList.value.total = res.data.total;
		dataList.value.items = res.data.rows;
	}
}

var newModel = ref({}), oldModel = ref({}),
	modelRules = ref({
		username: [{ required: true, message: "请输入账户名称", trigger: "blur" }],
		realname: [{ required: true, message: "请输入真实姓名", trigger: "blur" }],
		password: [{ required: true, message: "请设置登录密码", trigger: "blur" }],
		roles: [{ required: false, message: "请设选择角色", trigger: "blur" }],
	})

const create = function () {
	modelRules.value.password[0].required = true;
	showForm.value = true;
}

const update = function (row) {
	// 深拷贝，防止元数据被修改
	newModel.value = tools.deepCopy(row);
	oldModel.value = tools.deepCopy(row);
	modelRules.value.password[0].required = false;
	showForm.value = true;
}

const remove = function (row) {
	ElMessageBox.confirm(`是否删除 "${row.realname}"`, "提示", { type: "warning" }).then(async () => {
		processing.value = true;
		let res = await http.delete(`/rbac/admin/${row.id}`);
		processing.value = false;
		if (res && res.code === 200) {
			ElMessage({ type: "success", message: res.message });
			fetch();
		}
	}).catch(e => e);
}

const bindUpdateRow = function (row) {
	willUpdateRow = row;
}

const clearForm = function (done) {
	newModel.value = {};
	oldModel.value = {};
	typeof done === 'function' && done();
}

const hideForm = function () {
	adminForm.value.resetFields()
	EditDrawer.value.handleClose()
}

const updateState = function (state) {
	state = parseInt(state)
	let row = willUpdateRow;
	if (state === row.state) return false;
	const tip = `确定要将 "${row.realname}" 账户调整到 “${states[state].label}” 状态？`;
	ElMessageBox.confirm(tip, "提示", { type: "warning" }).then(async () => {
		processing.value = true;
		let res = await http.post('/rbac/admin/update-state', { id: row.id, state: state });
		processing.value = false;
		console.log(res);
		if (res && res.code === 200) {
			ElMessage({ type: "success", message: res.message });
			fetch();
		}
	}).catch(e => e);
}

const submitModel = async function () {
	if (JSON.stringify(oldModel.value) === JSON.stringify(newModel.value)) {
		ElMessage({ type: 'warning', message: '内容无变动，无需保存' })
		return;
	}
	submiting.value = true;
	let res;
	const model = newModel.value;
	if (model.id) {
		res = await http.put(`/rbac/admin/${model.id}`, model);
	} else {
		res = await http.post("/rbac/admin", model);
	}
	submiting.value = false;
	if (res && res.code === 200) {
		ElMessage({ type: 'success', message: res.message })
		EditDrawer.value.handleClose()
		fetch();
	} else {
		tools.httpFaildHandler(res)
	}
}

// 加载路由中的query参数
function loadQueries() {
	var queries = router.currentRoute.value.query;
	if (queries.username) query.value.username = queries.username;
	if (queries.realname) query.value.realname = queries.realname;
	if (queries.page) query.value.page = parseInt(queries.page);
	if (queries.size) {
		query.value.size = parseInt(queries.size);
		if (sizeOptions.indexOf(queries.size) !== false) {
			query.value.size = queries.size;
		}
	}
	queryParams = JSON.parse(JSON.stringify(query.value));
}

async function loadRoleList() {
	processing.value = true;
	let res = await http.get(`/rbac/role`);
	processing.value = false;
	if (res && res.code === 200) {
		rolesList.value = res.data.rows;
	} else {
		tools.httpFaildHandler(res)
	}
}

loadRoleList();
loadQueries();
fetch();

</script>
<template>
	<h1 class="page-title">账户管理</h1>
	<el-form :inline="true" :model="query" @submit.native.prevent="fetch" class="search-form">
		<el-form-item style="width: 150px;">
			<el-input v-model="query.username" @change="queryChanged = true" clearable placeholder="登录名" />
		</el-form-item>
		<el-form-item style="width: 150px;">
			<el-input v-model="query.realname" @change="queryChanged = true" clearable placeholder="姓名" />
		</el-form-item>
		<el-form-item>
			<el-button type="primary" :loading="fetching" :icon="Search" native-type="submit">查询</el-button>
		</el-form-item>
		<el-form-item fixed="right">
			<el-button type="success" :icon="Plus" @click="create">
				添加账户
			</el-button>
		</el-form-item>
	</el-form>

	<div class="list-box">
		<el-table :data="dataList.items" border :loading="fetching">
			<el-table-column prop="id" label="ID" width="100" />
			<el-table-column prop="username" label="用户名" />
			<el-table-column prop="realname" label="姓名" />
			<el-table-column prop="state" label="账户状态">
				<template #default="scope">
					<el-dropdown size="small" trigger="click" @command="updateState">
						<el-tag :type="states[scope.row.state].class" @click="bindUpdateRow(scope.row)">
							{{ states[scope.row.state].label }}<i class="el-icon-arrow-down el-icon--right"></i>
						</el-tag>
						<el-dropdown-menu slot="dropdown">
							<el-dropdown-item command="1">正常</el-dropdown-item>
							<el-dropdown-item command="2">禁用</el-dropdown-item>
							<el-dropdown-item command="0">删除</el-dropdown-item>
						</el-dropdown-menu>
					</el-dropdown>
				</template>
			</el-table-column>
			<el-table-column prop="created_at" label="创建时间" width="190" />
			<el-table-column prop="updated_at" label="更新时间" width="190" />
			<el-table-column fixed="right" label="操作" width="120">
				<template #default="scope">
					<el-button type="primary" size="small" :icon="Edit" @click="update(scope.row)" />
					<el-button type="danger" size="small" :icon="Delete" @click="remove(scope.row)" />
				</template>
			</el-table-column>
		</el-table>
		<Pagination :total="dataList.total" :page="query.page" :size="query.size" @pagination="fetch" />
	</div>

	<div class="editFormBox">
		<el-drawer ref="EditDrawer" :title="(oldModel.id ? '编辑' : '新建') + '账户'" size="39%"
			v-model="showForm" direction="rtl" :before-close="clearForm">
			<template #default>
				<div style="padding:10px;">
					<el-form :rules="modelRules" ref="adminForm" label-position="right" label-width="80px"
						:model="newModel">
						<el-form-item label="账户名称" prop="username">
							<el-input v-model="newModel.username" clearable placeholder="请输入账户名称（登录名）" />
						</el-form-item>
						<el-form-item label="真实姓名" prop="realname">
							<el-input v-model="newModel.realname" clearable placeholder="请输入真实姓名" />
						</el-form-item>
						<el-form-item label="登录密码" prop="password">
							<el-input v-model="newModel.password" :placeholder="oldModel.id ? '不输入则不修改' : '请设置登录密码'" />
						</el-form-item>
						<el-form-item label="权限角色" prop="roles">
							<el-select key="formRoleSelector" :teleported="false" v-model="newModel.roles" multiple clearable placeholder="请选择">
								<el-option v-for="item in rolesList" :key="item.id" :label="item.display_name"
									:value="item.id" />
							</el-select>
						</el-form-item>
					</el-form>
					<div class="form-buttons-container">
						<el-button @click="hideForm">取 消</el-button>
						<el-button type="primary" @click="submitModel()" :disabled="submiting" :loading="submiting"
							:icon="Check">
							{{ submiting ? '提交中 ...' : '保 存' }}
						</el-button>
					</div>
				</div>
			</template>
		</el-drawer>
	</div>
</template>